package uk.co.chrisdadswell.radioreminder;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SpinnerAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: Christian Dadswell
 * Date: 21/03/13
 * Time: 14:00
 */
public class fragmentStations extends ListFragment {
    OnStationSelectedListener mCallback;

    static final String APP_TAG = "rr ";
    static final String ACT_TAG = "fragmentStations: ";
    final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;
    static LinkedHashMap<String, String> lhmNationalStations = null;
    static LinkedHashMap<String, String> lhmRegionalStations = null;
    static LinkedHashMap<String, String> lhmLocalStations = null;
    static LinkedHashMap<String, String> currentStationsHashMap = null;
    static ArrayList<String> listStations;
    private ArrayAdapter<String> adapterStations;
    GetStations getAllStations;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnStationSelectedListener {
        /** Called by fragmentStations when a list item is selected
         * Returns stationName and stationScheduleUrl*/
        public void onStationSelected(String stationSelected, String stationScheduleUrl);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(APP_TAG, ACT_TAG + "... OnAttach ....");
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnStationSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnStationSelectedListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true); // used to give the activity an action bar specific to this fragment

        // If activity recreated (such as from screen rotate), restore
        // the previous station selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }

        View view = inflater.inflate(R.layout.fragment_stations, container, false);

        // Setup ActionBar spinner for station types
        SpinnerAdapter mSpinnerAdapter;
        mSpinnerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.station_types, android.R.layout.simple_spinner_dropdown_item);

        // Setup ActionBar
        ActionBar actionBar = getActivity().getActionBar();
        //actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.));
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar_underline)));
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() {

            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId) {
                listStations.clear();
                switch(itemPosition) {
                    case 0: // national
                        if(lhmNationalStations.size() != 0 || lhmNationalStations == null) {
                            lhmNationalStations = GetStationsHashMapFromFile(constants.nationalStations);
                            DisplayListView(listStations = ReturnArrayListFromLHMKeys(lhmNationalStations));
                        }
                        break;
                    case 1: // regional
                        if(lhmRegionalStations.size() != 0 || lhmRegionalStations == null) {
                            lhmRegionalStations = GetStationsHashMapFromFile(constants.regionalStations);
                            DisplayListView(listStations = ReturnArrayListFromLHMKeys(lhmRegionalStations));
                        }
                        break;
                    case 2: // local
                        if(lhmLocalStations.size() != 0 || lhmLocalStations == null) {
                            lhmLocalStations = GetStationsHashMapFromFile(constants.localStations);
                            DisplayListView(listStations = ReturnArrayListFromLHMKeys(lhmLocalStations));
                        }
                        break;
                }
                return false;
            }
        };
        /** Setting dropdown items and item navigation listener for the actionbar */
        getActivity().getActionBar().setListNavigationCallbacks(mSpinnerAdapter, navigationListener);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lhmNationalStations = GetStationsHashMapFromFile(constants.nationalStations);
        lhmRegionalStations = GetStationsHashMapFromFile(constants.regionalStations);
        lhmLocalStations = GetStationsHashMapFromFile(constants.localStations);
        DisplayListView(listStations = ReturnArrayListFromLHMKeys(lhmNationalStations));
/*
        listview_Stations = getListView();
        listview_Stations.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //@Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Intent byPodcast_intent = new Intent();
                String selectedStation =(String) (listview_Stations.getItemAtPosition(position));
                //byPodcast_intent.setClass(view.getContext(), Activity_ByPodcast.class);
                //byPodcast_intent.putExtra("SelectedStation", selectedStation);
                //startActivity(byPodcast_intent);
            }
        });*/
    }

    @Override
    public void onStart() {
        super.onStart();
        if(GotStationFiles()) {
            Log.d(APP_TAG, ACT_TAG + "We have station files");
        }else{
            Log.d(APP_TAG, ACT_TAG + "We had to download station files");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Save the current article selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        String selectedStation = (String) l.getItemAtPosition(position);
        // Get stationScheduleUrl to pass back to activityDashboard
        String stationScheduleUrl = GetDefaultStationScheduleUrlFromStationsHashMap(selectedStation, currentStationsHashMap);

        if (mCallback != null) {
            mCallback.onStationSelected(selectedStation, stationScheduleUrl);
        }
        // TWO PANE LAYOUT NOTE
        // Set the item as checked to be highlighted when in two-pane layout
        //getListView().setItemChecked(position, true);
    }

    // ADDITIONAL MENUS
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.stations_menu, menu);
    }

    // MENU SELECTORS
    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        switch (item.getItemId()){

            case android.R.id.home:
                Intent intent = new Intent(getActivity(), activityDashboard.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;

            /*case R.id.menu_about:
                Intent aboutActivity = new Intent(Activity_Dashboard.this, Activity_About.class);
                startActivity(aboutActivity);
                return true;

            case R.id.menu_refresh:
                downloadNewListingsDialog(this.getResources().getString(R.string.download_listings_dialog_title), this.getResources().getString(R.string.download_listings_dialog_body));
                refresh.setActionView(R.layout.actionbar_indeterminate_progress);
                return true;

            case R.id.menu_blog:
                Intent blogURL_intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(Constants.urlBlog));
                startActivity(blogURL_intent);
                return true;

            case R.id.menu_gplus:
                Intent gplusURL_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlGooglePlus));
                startActivity(gplusURL_intent);
                return true;

            case R.id.menu_rss:
                Intent rssURL_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlRss));
                startActivity(rssURL_intent);
                return true;

            case R.id.menu_twitter:
                Intent twitter_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlTwitter));
                startActivity(twitter_intent);
                return true;*/
        }
        return false;
    }
    // Async task to get stations to json if required

    class GetStations extends AsyncTask<Void, Integer, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            GetStations();
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            //Toast.makeText(activityDashboard.this,"Stations downloaded", Toast.LENGTH_SHORT).show();
        }
    }

    public void GetStations() {
        if(isInternetOn()) {
            functions_Parser.GetAllStations();
        }else{
            // Dialog needed
        }
    }

    private boolean GotStationFiles() {
        // Have we got files already?
        int stationFileCount = new File(constants.stationsDir).listFiles().length;
        if(stationFileCount == 3) {
            return true;
        }else{
            getAllStations = new GetStations();
            getAllStations.execute();
        }
        return false;
    }

    // GET STATIONS HASHMAP FROM JSON
    private LinkedHashMap<String, String> GetStationsHashMapFromFile(String locality) {
        LinkedHashMap<String, String> lhm_Stations;
        lhm_Stations = functions_Json.ReturnLinkedHashMapFromJson(constants.stationsDir, locality);

        // set the current stations hashmap
        currentStationsHashMap = lhm_Stations;
        return lhm_Stations;
    }

    // RETURNS A STATION SCHEDULE URL FROM HASHMAP
    public static String GetDefaultStationScheduleUrlFromStationsHashMap(String stationName, LinkedHashMap stations) {
        String stationDefaultScheduleUrl = stations.get(stationName).toString();
        return stationDefaultScheduleUrl;
    }

    //  RETURNS AN ARRAYLIST OF STATION NAMES
    public static ArrayList ReturnArrayListFromLHMKeys (LinkedHashMap lhm) {
        ArrayList stationNameList = new ArrayList( );

        Set keySet = lhm.keySet( );
        Iterator keyIterator = keySet.iterator( );
        while( keyIterator.hasNext( ) ) {
            Object key = keyIterator.next( );
            stationNameList.add(key.toString());
        }
        return stationNameList;
    }

    public void DisplayListView(ArrayList aList) {
        adapterStations = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, aList);
        getListView().setAdapter(adapterStations);
        adapterStations.notifyDataSetChanged();
    }

    // CHECK INTERNET METHOD
    public final boolean isInternetOn() {
        Log.d(APP_TAG, ACT_TAG + "Checking connectivity ...");
        ConnectivityManager connec = null;
        connec =  (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if ( connec != null){
            Log.d(APP_TAG, ACT_TAG + "We have internet");
            NetworkInfo result = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (result != null && result.isConnectedOrConnecting());
            return true;
        }
        Log.d(APP_TAG, ACT_TAG + "No internet connection found");
        return false;
    }
}
